#include <unistd.h>
#include <errno.h>
#include <pthread.h>

#include "MobsBuf.h"

void *mobs_producer(void*args)
{
    uintptr_t wuid = (uintptr_t)args;
    printf("producer uid = 0x%08lx,arg = %p\n",wuid,args);

    int ret = 0,woid;
    char data[1024];
    size_t cnt = 0;
    while(1)
    {//test write
	ret = mobs_start(wuid,0);
	printf("~~~write start ret = %d\n",ret);
	if(ret < 0) 
	{
	    break;
	    //exit(EXIT_FAILURE);
	}

	snprintf(data,sizeof(data),"hello mobs - msg %02zu!",cnt++);

	woid = ret;
	ret = mobs_write(wuid,woid,data,strlen(data));
	printf("###write data:%s ret = %d\n",data,ret);
	if(ret < 0)
	{
	    break;
	    //exit(EXIT_FAILURE);
	}
	mobs_finish(wuid,woid);

	sleep(5);
    }
    return NULL;
}
void *mobs_consumer(void*args)
{
    uintptr_t ruid = (uintptr_t)args;
    printf("consumer uid = 0x%08lx,arg = %p\n",ruid,args);

    char data[1024];
    int ret = 0,roid;
    while(1)
    { //test read
	ret = mobs_start(ruid,0);
	printf("~~~read start ret = %d\n",ret);
	if(ret == MOBS_ERR_EMPTY)
	{
	    sleep(2);
	    continue;
	}
	else if(ret < 0) exit(EXIT_FAILURE);

	roid = ret;
	memset(data,0,sizeof(data));
	ret = mobs_read(ruid,roid,data,sizeof(data));
	printf("###read data:%s ret = %d\n",data,ret);
	if(ret == MOBS_ERR_INTERRUPTED)
	{// next
	}
	else if(ret < 0)
	{
	    break;
	    //exit(EXIT_FAILURE);
	}
	mobs_finish(ruid,roid);
    }
    return NULL;
}

int main(int argc,char *argv[])
{
    int ret = 0;
    uintptr_t wuid,ruid;
    
    mobs_unlink("/tmp/buf03.mobs");

    wuid = mobs_open("producer","/tmp/buf03.mobs",
	    MOBS_FLAG_CREATE|MOBS_FLAG_WRONLY|MOBS_FLAG_PRIVATE|MOBS_FLAG_THREADS,1024*1024,1024,4096);
    ruid = mobs_open("consumer","/tmp/buf03.mobs",
	    MOBS_FLAG_CREATE|MOBS_FLAG_RDONLY|MOBS_FLAG_PRIVATE|MOBS_FLAG_THREADS,1024*1024,1024,4096);
    printf("open mobs wuid = 0x%08lx,ruid = 0x%08lx\n",wuid,ruid);

    if(wuid == 0 || ruid == 0)
	exit(EXIT_FAILURE);

    pthread_t wtid,rtid;

    ret = pthread_create(&wtid,NULL,mobs_producer,(void*)wuid);
    ret = pthread_create(&rtid,NULL,mobs_consumer,(void*)ruid);

    pthread_join(wtid,NULL);
    pthread_join(rtid,NULL);

    mobs_close(wuid);
    printf("close mobs wuid = 0x%08lx\n",wuid);
    mobs_close(ruid);
    printf("close mobs ruid = 0x%08lx\n",ruid);

    return ret;
}

